package cn.bistu.cs.music;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;

import android.os.Bundle;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import cn.bistu.cs.music.Service.DownloadService;
import cn.bistu.cs.music.gson.SelectMusicbyName;
import cn.bistu.cs.music.recyclerAdapter.Music;
import cn.bistu.cs.music.recyclerAdapter.MusicAdapter;
import cn.bistu.cs.music.util.HttpUtil;
import cn.bistu.cs.music.util.Utility;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MusicActivity extends AppCompatActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
    private RecyclerView recyclerView;
    private EditText searchMusic;
    private Button searchMusicButton;
    private MusicAdapter adapter;
//    private MediaPlayer mediaPlayer = new MediaPlayer();
    public String selectMusicID="";//待搜索的歌曲的ID号
    public String selectMusicName="";//待搜索的歌曲的名字
    private SwipeRefreshLayout swipeRefreshLayout;
    List<Music> arrList = new ArrayList();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music);
        initView();//初始化控件
        initData();//初始化数据

    }

    /**
     *初始化控件
     */
    private void initView(){
        recyclerView =  findViewById(R.id.recycler);
        searchMusic = findViewById(R.id.searchMusic);
        searchMusicButton = findViewById(R.id.searchMusicButton);
        swipeRefreshLayout = findViewById(R.id.swipeRefresh);
        searchMusicButton.setOnClickListener(this);
        swipeRefreshLayout.setOnRefreshListener(this);
    }
    public void onClick(View view){
        switch (view.getId()){
            case R.id.searchMusicButton:
                String musicName = searchMusic.getText().toString();
                if(musicName!=null&&!"".equals(musicName)){
                    String url_name = "http://api.we-chat.cn/search?" + "keywords="+musicName;
                    Log.e("搜索歌曲:",url_name);
                    HttpUtil.sendOkHttpRequest(url_name, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                        }
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            SelectMusicbyName selectMusicbyName = Utility.jsonTOSelectMusic(response);

                            if(selectMusicbyName!=null&&selectMusicbyName.getCode()==200){
                                getDownloadURL(selectMusicbyName);
                            }else{
                                Looper.prepare();
                                Log.e("response=",response+"");
                                Toast.makeText(MusicActivity.this,"服务器响应错误",Toast.LENGTH_SHORT).show();
                                Looper.loop();
                            }
                        }
                    });

                }else{
                    Toast.makeText(MusicActivity.this,"请输入歌曲名字再搜索",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }

    }
    private void getDownloadURL(SelectMusicbyName selectMusicbyName){
        selectMusicID = selectMusicbyName.getResult().getSongs().get(0).getId();
        selectMusicName = selectMusicbyName.getResult().getSongs().get(0).getName();
        //跳转，根据歌曲的id进行下载
        Intent  intent = new Intent(MusicActivity.this, DownloadService.class);
        intent.putExtra("download_url","https://cloud-music-api-f494k233x-mgod-monkey.vercel.app/song/url?id="+selectMusicID);
        intent.putExtra("musicName",selectMusicName);
        startService(intent);
    }
    /**
     * 初始化数据
     */
    @SuppressLint("Range")
    private void initData(){
        Cursor cursor = getApplicationContext().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,null,null,null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        Log.e("查询到的歌曲总数：",cursor.getCount()+"首");
        while(cursor.moveToNext()){
            String musicTitle = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            String musicSinger = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            Music music = new Music(musicTitle,musicSinger);
            Log.e("arrlist:",music.getMusicName());
            arrList.add(music);
        }
        cursor.close();
        //适配器
        adapter = new MusicAdapter(arrList);
        //瀑布流管理器
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(layoutManager);
    }

    @Override
    public void onRefresh() {
        arrList.clear();
        initData();
//        adapter.notifyDataSetChanged();
        swipeRefreshLayout.setRefreshing(false);
    }
}
//
//    /**
//     * 拷贝文件到SD中，filePath assets中文件路径
//     * @param c
//     * @param filePath
//     * @param dst
//     * @return
//     */
//    public String mergeFile(Context c, String filePath, String dst) {
//        File fileone = new File(dst);
//        System.out.println("sd卡中"+dst+"文件是否存在:" + fileone.exists());
//        if (!fileone.exists()) {
//            OutputStream out;
//            try {
////                fileone.createNewFile();
////                Log.e("创建新文件",dst+"");
//                out = new FileOutputStream(dst);
//                byte[] buffer = new byte[2048];
//                InputStream in;
//                int readLen = 0;
//                // 获得输入流 ,注意文件的路径 此文件路径为在程序的assets目录下
//                in = c.getResources().getAssets().open(filePath);
//                Log.e("Assets文件","：打开成功，开始写入SD卡");
//                while ((readLen = in.read(buffer)) != -1) {
//                    out.write(buffer, 0, readLen);
//                }
//                out.flush();
//                in.close();
//                // 把所有小文件都进行写操作后才关闭输出流，这样就会合并为一个文件了
//                out.close();
//            } catch (IOException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//        }
////        System.out.println("dst 文件路径 ： " + dst);
//        return dst;
//    }
//    /**
//     * 在SD中新建一个MP3文件 fileNames参数为文件名
//     * @param fileNames
//     * @return MP3的绝对路径
//     */
//    public String getSDPath(String fileNames) {
////        File sdDir = null;
//        String fileName = null;
//        // 判断sd卡是否存在
//        boolean sdCardExist = Environment.getExternalStorageState().equals(
//                android.os.Environment.MEDIA_MOUNTED);
////        Log.e("sd根目录：", String.valueOf(Environment.getExternalStorageDirectory()));
//        if (sdCardExist) {
//            Log.e("SD","存在");
////            sdDir = Environment.getExternalStorageDirectory();// 获取根目录
//            fileName = "/data/data/cn.bistu.cs.music/player/"+ fileNames;
//            try {
//                File file = new File(fileName);
//                Log.e("创建新的MP3文件是否成功",""+file.createNewFile());
//            }catch (IOException e){
//                Log.e("创建新的MP3文件","报错");
//                e.printStackTrace();
//            }
//        }else{
//            Log.e("SD","不存在");
//        }
//        return fileName;
//    }

//    @Override
//    public void onClick(View v) {
//        switch (v.getId()){
//            case R.id.play:
//                if(!mediaPlayer.isPlaying())
//                    mediaPlayer.start();
//                break;
//            case R.id.pause:
//                if(mediaPlayer.isPlaying()){
//                    mediaPlayer.pause();
//                }
//                break;
//            case R.id.stop:
//                if (mediaPlayer.isPlaying())
//                    mediaPlayer.stop();
//                break;
//        }
//    }
//
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        if(mediaPlayer!=null){
//            mediaPlayer.stop();
//            mediaPlayer.release();
//        }
//    }